/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vastcm.stuhealth.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.vastcm.stuhealth.client.entity.CheckResult;
import com.vastcm.stuhealth.client.entity.RptTbAge;
import com.vastcm.stuhealth.client.entity.RptTbGrade;
import com.vastcm.stuhealth.client.entity.RptZbAge;
import com.vastcm.stuhealth.client.entity.RptZbGrade;
import com.vastcm.stuhealth.client.entity.School;
import com.vastcm.stuhealth.client.entity.SchoolTreeNode;
import com.vastcm.stuhealth.client.entity.ServerSetting;
import com.vastcm.stuhealth.client.entity.UploadLog;
import com.vastcm.stuhealth.client.entity.core.CoreEntity;
import com.vastcm.stuhealth.client.entity.service.ICheckResultService;
import com.vastcm.stuhealth.client.entity.service.IRptTbAgeService;
import com.vastcm.stuhealth.client.entity.service.IRptTbGradeService;
import com.vastcm.stuhealth.client.entity.service.IRptZbAgeService;
import com.vastcm.stuhealth.client.entity.service.IRptZbGradeService;
import com.vastcm.stuhealth.client.entity.service.ISchoolService;
import com.vastcm.stuhealth.client.entity.service.IServerSettingService;
import com.vastcm.stuhealth.client.entity.service.IUploadLogService;
import com.vastcm.stuhealth.client.framework.Request;
import com.vastcm.stuhealth.client.framework.exception.ConnectionException;
import com.vastcm.stuhealth.client.framework.exception.RequestException;
import com.vastcm.stuhealth.client.framework.ui.KernelUI;
import com.vastcm.stuhealth.client.utils.ExceptionUtils;
import com.vastcm.stuhealth.client.utils.SecurityUtils;
import com.vastcm.stuhealth.framework.Response;
import com.vastcm.stuhealth.framework.ResponseContent;
import com.vastcm.stuhealth.framework.ResponseUtils;

import java.awt.Dimension;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author house
 */
public class UploadPanel extends KernelUI {
    
    private Logger logger = LoggerFactory.getLogger(UploadPanel.class);
    private SchoolTreeNode schClass;
    private ProgressPanel progressPanel;
   
    /**
     * Creates new form UploadPanel
     */  
    public UploadPanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnUpload = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        txtSchool = new javax.swing.JTextField();
        btnSelectSch = new javax.swing.JButton();

        setPreferredSize(new Dimension(500, 180));
        setLayout(new java.awt.BorderLayout());

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        btnUpload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/upload.png"))); // NOI18N
        btnUpload.setText("上传");
        btnUpload.setFocusable(false);
        btnUpload.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnUpload.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnUpload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUploadActionPerformed(evt);
            }
        });
        jToolBar1.add(btnUpload);

        add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jPanel1.setLayout(null);

        jLabel1.setText("用户名");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 20, 80, 25);
        jPanel1.add(txtUser);
        txtUser.setBounds(80, 20, 120, 25);

        jLabel2.setText("密码");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(230, 20, 80, 25);
        jPanel1.add(txtPassword);
        txtPassword.setBounds(300, 20, 120, 25);

        jLabel3.setText("学校");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(20, 60, 80, 25);

        txtSchool.setEditable(false);
        txtSchool.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSchoolActionPerformed(evt);
            }
        });
        jPanel1.add(txtSchool);
        txtSchool.setBounds(80, 60, 190, 25);

        btnSelectSch.setText("选择..");
        btnSelectSch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectSchActionPerformed(evt);
            }
        });
        jPanel1.add(btnSelectSch);
        btnSelectSch.setBounds(270, 60, 60, 25);

        add(jPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    public ISchoolService getSchoolService() {
    	return AppContext.getBean("schoolService", ISchoolService.class);
    }
    
    protected void writeUploadLog(String year, String term, String schoolCode, String user, Date date) {
    	IUploadLogService uploadLogSrv = AppContext.getBean("uploadLogService", IUploadLogService.class);
    	UploadLog log = new UploadLog();
    	log.setYear(year);
    	log.setTerm(term);
    	log.setSchoolCode(schoolCode);
    	log.setUploadUser(user);
    	log.setUploadDate(new java.sql.Date(date.getTime()));
    	uploadLogSrv.save(log);
    }
    
    private void btnUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadActionPerformed
        
        try {
            final String username = txtUser.getText().trim();
            if(username == null || username.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请输入 用户名！");
                return;
            }
            char[] password = txtPassword.getPassword();
            if(password == null || password.length == 0) {
                JOptionPane.showMessageDialog(this, "请输入 密码！");
                return;
            }
            if(schClass == null) {
                JOptionPane.showMessageDialog(this, "请选择学校！");
                return;
            }
                    
            final String schoolBh = schClass.getCode();
            School school = getSchoolService().getByCode(schoolBh);
            Request reqAuth = new Request("/auth");
            reqAuth.setParam("username", username);
//            logger.info("password: " + String.valueOf(password));
            reqAuth.setParam("password", SecurityUtils.cryptPassword(String.valueOf(password)));
            reqAuth.setParam("schoolCode", schoolBh);
            reqAuth.setParam("schoolSecCode", school.getSecCode());
            Response respAuth = reqAuth.send();
            if(respAuth.getRetCode() != ResponseUtils.RETCODE_OK) {
                String msg = "ERROR [" + respAuth.getRetCode() + "]-" + respAuth.getRetMsg();
                logger.error(msg);
                JOptionPane.showMessageDialog(this, msg);
                return;
            }
//            final String sessionId = respAuth.getSessionId();
            
            Request req1 = new Request("/CheckResultExistence");
//            req1.setParam("sessionId", sessionId);
            req1.setParam("year", String.valueOf(GlobalVariables.getGlobalVariables().getYear()));
            req1.setParam("schoolBh", schoolBh);
            Response res1 = req1.send();
            String isExist = res1.getExContent().get("isExist");
            if(isExist != null && isExist.equalsIgnoreCase("true")) {
                int confirm = JOptionPane.showConfirmDialog(this, 
                        "该校本学年已上传过数据，请确定是否重新上传？", "确认", JOptionPane.YES_NO_OPTION);
                if(confirm != JOptionPane.OK_OPTION) {
                    return;
                }
                Request req2 = new Request("/DeleteCheckResult");
//                req2.setParam("sessionId", sessionId);
                req2.setParam("year", String.valueOf(GlobalVariables.getGlobalVariables().getYear()));
                req2.setParam("schoolBh", schoolBh);
                Response res2 = req2.send();
                logger.info(res2.getRetMsg());
            }
            
            GlobalVariables gv = GlobalVariables.getGlobalVariables();
            final String year = String.valueOf(gv.getYear());
            final String term = String.valueOf(gv.getTerm());
            logger.info("schoolBh=" + schoolBh + ", schoolName=" + schClass.getName() + ", year=" + year);
            ICheckResultService resultService = AppContext.getBean("checkResultService", ICheckResultService.class);
            final List<CheckResult> checkResultLs = resultService.getBySchool(schoolBh, year, term);
            IRptTbAgeService rptTbAgeService = AppContext.getBean("rptTbAgeService", IRptTbAgeService.class);
            final List<RptTbAge> rptTbAgeLs = rptTbAgeService.getBySchoolBh(schoolBh, year);
            IRptTbGradeService rptTbGradeService = AppContext.getBean("rptTbGradeService", IRptTbGradeService.class);
            final List<RptTbGrade> rptTbGradeLs = rptTbGradeService.getBySchoolBh(schoolBh, year);
            IRptZbAgeService rptZbAgeService = AppContext.getBean("rptZbAgeService", IRptZbAgeService.class);
            final List<RptZbAge> rptZbAgeLs = rptZbAgeService.getBySchoolBh(schoolBh, year);
            IRptZbGradeService rptZbGradeService = AppContext.getBean("rptZbGradeService", IRptZbGradeService.class);
            final List<RptZbGrade> rptZbGradeLs = rptZbGradeService.getBySchoolBh(schoolBh, year);
            progressPanel 
//                    = new ProgressPanel((JFrame)SwingUtilities.getWindowAncestor(this));
            			= new ProgressPanel(null);
            progressPanel.setProgressKeeper(new Runnable() {

                @Override
                public void run() {
                	try {
                		int checkResultCount = uploadData(checkResultLs, "/UploadCheckResult", "体检结果");
                        int rptTbAgeCount    = uploadData(rptTbAgeLs, 	 "/UploadRptTbAge",   "统计表1");
                        int rptTbGradeCount  = uploadData(rptTbGradeLs,  "/UploadRptTbGrade", "统计表2");
                        int rptZbAgeCount    = uploadData(rptZbAgeLs, 	 "/UploadRptZbAge",   "统计表3");
                        int rptZbGradeCount  = uploadData(rptZbGradeLs,  "/UploadRptZbGrade", "统计表4");
                        final StringBuilder msg = new StringBuilder();
                        msg.append("成功上传 ");
                        msg.append(checkResultCount).append(" 条体检结果记录； ");
                        msg.append(rptTbAgeCount + rptTbGradeCount + rptZbAgeCount + rptZbGradeCount).append(" 条统计记录！");
                        writeUploadLog(year, term, schoolBh, username, new Date());
                        SwingUtilities.invokeLater(new Runnable() {
							
							@Override
							public void run() {
								progressPanel.dispose();
								JOptionPane.showMessageDialog(UploadPanel.this, msg);
							}
						});                       
                	}
                	catch(Exception e) {
                		ExceptionUtils.writeExceptionLog(logger, e);
                		SwingUtilities.invokeLater(new Runnable() {
							
							@Override
							public void run() {
								JOptionPane.showMessageDialog(UploadPanel.this, "数据上传失败！");
		                		progressPanel.dispose();
							}
						});    
                		
                	}
                	return;
                }
            });
            
            progressPanel.setVisible(true);
  
        } 
        catch (ConnectionException ex) {
            ExceptionUtils.writeExceptionLog(logger, ex);
            JOptionPane.showMessageDialog(this, "连接失败！");
        } 
        catch (RequestException ex) {
            ExceptionUtils.writeExceptionLog(logger, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
            
    }//GEN-LAST:event_btnUploadActionPerformed
    
    public int uploadData(List<? extends CoreEntity> dataLs, String url, final String message) throws ConnectionException, RequestException {
    	final int count = dataLs.size();
        for(int i = 0; i < count; i++ ) {
            CoreEntity rs = dataLs.get(i);
            String json = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(rs);
            logger.info("Sending json: " + json);
            Request req3 = new Request(url);
//            req3.setParam("sessionId", sessionId);
            req3.setParam(json, json);
            req3.setParam("data", json);
            Response res3 = req3.send();
            logger.info(res3.getRetMsg());
            final int iFinal = i;
            SwingUtilities.invokeLater(new Runnable() {
				
				@Override
				public void run() {
					progressPanel.getProgressBar().setValue(iFinal*100/count);
			        progressPanel.getLblDescription().setText("共 " + count + " 条 " + message + " 记录要上传，已上传 " + iFinal + " 条。");
				}
			});
            
        }
        return count;
    }
    
    public int uploadData_todo(List<? extends CoreEntity> dataLs, String url, final String message) throws ConnectionException, RequestException {
    	final int count = dataLs.size();
    	Type typeOfSrc = new TypeToken<Collection<CoreEntity>>(){}.getType();
    	new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(dataLs, typeOfSrc);
        for(int i = 0; i < count; i++ ) {
            CoreEntity rs = dataLs.get(i);
            String json = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(rs);
            logger.info("Sending json: " + json);
            Request req3 = new Request(url);
//            req3.setParam("sessionId", sessionId);
            req3.setParam(json, json);
            req3.setParam("data", json);
            Response res3 = req3.send();
            logger.info(res3.getRetMsg());
            final int iFinal = i;
            SwingUtilities.invokeLater(new Runnable() {
				
				@Override
				public void run() {
					progressPanel.getProgressBar().setValue(iFinal*100/count);
			        progressPanel.getLblDescription().setText("共 " + count + " 条 " + message + " 记录要上传，已上传 " + iFinal + " 条。");
				}
			});
            
        }
        return count;
    }

    private void txtSchoolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSchoolActionPerformed
        logger.info("txtSchoolActionPerformed....");
    }//GEN-LAST:event_txtSchoolActionPerformed

    private void btnSelectSchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectSchActionPerformed
        selectClass();
        if(schClass != null) {
            if(schClass.getType() != SchoolTreeNode.TYPE_SCHOOL) {
                JOptionPane.showMessageDialog(this, "请选择学校节点！");
                return;
            }
            txtSchool.setText(schClass.getName());
        }
    }//GEN-LAST:event_btnSelectSchActionPerformed

    protected void selectClass() {
//        UIFactory.create(SchoolTreePanel, UIType.TAB, null, null)
        SchoolTreePanel destSchool = new SchoolTreePanel();
        destSchool.setToolbarVisible(false);
        destSchool.setMergedSchoolVisible(false);
        destSchool.setIsDisplayClass(false);
        destSchool.displayUploadMsg();
        destSchool.displaySecCodeMsg();
        SelectorDialog<SchoolTreeNode> selectorUI = new SelectorDialog<SchoolTreeNode>(null, true);
        selectorUI.setUI(destSchool);
        selectorUI.setVisible(true);
        schClass = selectorUI.getValue();
    }
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSelectSch;
    private javax.swing.JButton btnUpload;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtSchool;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
